﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Data;
using System.IO;
using System.Linq;
using Cinch;
using System.Windows.Threading;
using System.Configuration;


namespace Anata.Client
{
    /// <summary>
    /// </summary>
    public class FreeGiftSelectViewModel : ViewModelBase
    {
        #region Data
        #region Data.Primitives
        private int? idLayanan;

        private String filterKeyword = "";

        private bool isAllLoaded = false;
        private int pageLoaded = 0;
        private DispatcherTimer filterTimer;
        #endregion

        #region Data.Rules
        #endregion

        #region Data.VMs
        private DispatcherNotifiedObservableCollection<FreeGiftThumbnailViewModel> freeGifts;
        private ICollectionView freeGiftsCV;
        #endregion

        #region Data.Services
        private IViewAwareStatus viewAwareStatusService;
        private IMessageBoxService messageBoxService;
        private IUIVisualizerService uiVisualizerService;
        private IReferenceProvider referenceProvider;
        #endregion

        #endregion


        #region Constructor
        [ImportingConstructor]
        public FreeGiftSelectViewModel(
            IMessageBoxService messageBoxService,
            IUIVisualizerService uiVisualizerService,
            IReferenceProvider referenceProvider)
        {
            #region Constructor.SetupServices
            this.messageBoxService = messageBoxService;
            this.uiVisualizerService = uiVisualizerService;
            //this.viewAwareStatusService = viewAwareStatusService;
            this.referenceProvider = referenceProvider;
            //this.viewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded;
            #endregion

            #region Constructor.SetupCommands
            //KonsumenNewCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenNewCommand, ExecuteKonsumenNewCommand);
            //KonsumenRefreshCommand = new SimpleCommand<Object, Object>(CanExecuteKonsumenRefreshCommand, ExecuteKonsumenRefreshCommand);
            FilterKeyUpCommand = new SimpleCommand<Object, Object>(CanExecuteFilterKeyUpCommand, ExecuteFilterKeyUpCommand);
            FreeGiftMouseLeftButtonUpCommand = new SimpleCommand<Object, Object>(CanExecuteFreeGiftMouseLeftButtonUpCommand, ExecuteFreeGiftMouseLeftButtonUpCommand);
            #endregion

            #region Constructor.SetupDataWrappers
            #endregion

            #region Constructor.SetupValidationRules
            #endregion

            #region Constructor.SetupVMs
            FreeGifts = new DispatcherNotifiedObservableCollection<FreeGiftThumbnailViewModel>();
            FreeGiftsCV = CollectionViewSource.GetDefaultView(freeGifts);
            #endregion

            Mediator.Instance.Register(this);

            #region Constructor.Filter
            filterTimer = new DispatcherTimer();
            filterTimer.Interval = TimeSpan.FromMilliseconds(
                Int32.Parse(ConfigurationManager.AppSettings["FilterResponsiveness"].ToString()));
            filterTimer.Tick += new EventHandler(LazyFilterCallback);
            #endregion

        }
        #endregion

        #region Public Properties
        #region Public.Commands
        public SimpleCommand<Object, Object> FilterKeyUpCommand { get; private set; }
        public SimpleCommand<Object, Object> FreeGiftMouseLeftButtonUpCommand { get; private set; }
        #endregion

        #region Public.ViewMode
        #endregion

        #region Public.Data
        /// <summary>
        /// </summary>
        static PropertyChangedEventArgs filterKeywordChangeArgs =
            ObservableHelper.CreateArgs<FreeGiftSelectViewModel>(x => x.FilterKeyword);
        public String FilterKeyword
        {
            get { return filterKeyword; }
            set
            {
                filterKeyword = value;
                NotifyPropertyChanged(filterKeywordChangeArgs);
                LazyFilter();
            }
        }
        #endregion

        #region Public.CachedCollection
        #endregion

        #region Public.DataVMs
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs freeGiftsChangeArgs =
            ObservableHelper.CreateArgs<FreeGiftSelectViewModel>(x => x.FreeGifts);

        public DispatcherNotifiedObservableCollection<FreeGiftThumbnailViewModel> FreeGifts
        {
            get { return freeGifts; }
            set
            {
                freeGifts = value;
                NotifyPropertyChanged(freeGiftsChangeArgs);
            }
        }
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs freeGiftsCVChangeArgs =
            ObservableHelper.CreateArgs<FreeGiftSelectViewModel>(x => x.FreeGiftsCV);

        public ICollectionView FreeGiftsCV
        {
            get { return freeGiftsCV; }
            set
            {
                freeGiftsCV = value;
                NotifyPropertyChanged(freeGiftsCVChangeArgs);
            }
        }
        #endregion
        #endregion

        #region Command Handlers
        /// <summary>
        /// </summary>
        private bool CanExecuteFilterKeyUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteFilterKeyUpCommand(Object args)
        {
            LazyFilter();
        }

        /// <summary>
        /// </summary>
        private bool CanExecuteFreeGiftMouseLeftButtonUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteFreeGiftMouseLeftButtonUpCommand(Object args)
        {
            if (freeGiftsCV.CurrentPosition > -1)
            {
                CloseActivePopUpCommand.Execute(true);
            }
        }
        #endregion

        #region IViewStatusAwareInjectionAware Members
        #endregion

        #region Private Methods
        #region PrivateMethods.ViewLoaded
        private void ViewAwareStatusService_ViewLoaded()
        {
            LoadFreeGifts();
        }
        #endregion

        #region PrivateMethods.Filter
        private void LazyFilter()
        {
            filterTimer.Stop();
            filterTimer.Start();
            Console.WriteLine("typing");
        }
        private void LazyFilterCallback(object sender, EventArgs e)
        {
            Console.WriteLine("stopped typing, filtering with keyword: " + filterKeyword);
            filterTimer.Stop();
            if (filterKeyword != "")
            {
                freeGiftsCV.Filter = new Predicate<object>(LazyFilterPredicate);
            }
            else
            {
                freeGiftsCV.Filter = null;
            }
        }
        private bool LazyFilterPredicate(object row)
        {
            FreeGiftThumbnailViewModel ptvm = row as FreeGiftThumbnailViewModel;
            return (ptvm.Nama.ToLower().Contains(filterKeyword.ToLower()));
        }
        #endregion

        #region PrivateMethods.Loader
        /// <summary>
        /// loader
        /// </summary>
        private void LoadFreeGifts()
        {
            referenceProvider.LazyFetchFreeGifts(pageLoaded, PostLoadFreeGifts);
        }

        /// <summary>
        /// post loader
        /// </summary>
        private void PostLoadFreeGifts(List<FreeGift> dbFreeGifts)
        {
            //rekursif sampai semua diload
            int pageSize = Int32.Parse(ConfigurationManager.AppSettings["LazyLoadPageSize"].ToString());
            FreeGiftThumbnailViewModel ftvm = null;
            foreach (var item in dbFreeGifts)
            {
                if (IsValidFreeGift(item))
                {
                    ftvm = new FreeGiftThumbnailViewModel();
                    ftvm.IdFreeGift = item.IdFreeGift;
                    ftvm.IdLayanan = item.IdLayanan;
                    ftvm.IdCabang = item.IdCabang;
                    ftvm.Nama = item.Nama;
                    ftvm.IdJenisStok = item.IdJenisStok;
                    ftvm.Jumlah = item.Jumlah;
                    ftvm.IsAktif = item.IsAktif;
                    freeGifts.Add(ftvm);
                    Console.WriteLine("Nama: " + item.Nama);
                }
            }

            if (dbFreeGifts.Count != pageSize)
            {
                //basis
                //sudah habis, done loading
                isAllLoaded = true;
            }
            else
            {
                //rekurens
                ++pageLoaded;
                LoadFreeGifts();
            }
        }
        #endregion

        #region PrivateMethods.ValidityChecker
        private bool IsValidFreeGift(FreeGift freeGift)
        {
            bool retval = true;
            retval = !idLayanan.HasValue
                || (idLayanan == freeGift.IdLayanan && freeGift.IsAktif);
            return retval;
        }
        #endregion
        #endregion

        #region PublicMethods
        public void SetCriteria(int? idLayanan)
        {
            this.idLayanan = idLayanan;
            LoadFreeGifts();
        }
        #endregion
    }

}
//        #region Data

//        //private ViewMode currentViewMode = ViewMode.AddMode;

//        #region Data.Primitives
//        #endregion

//        //private IEnumerable<DataWrapperBase> cachedListOfDataWrappers;

//        #region Data.Rules
//        #endregion

//        #region Data.VMs
//        private FreeGiftViewModel selectedFreeGift;
//        private FreeGiftFilterViewModel freeGiftFilter;
//        #endregion

//        #region Data.Services
//        private IMessageBoxService messageBoxService;
//        private IUIVisualizerService uiVisualizerService;
//        #endregion

//        #endregion

//        #region Constructor
//        [ImportingConstructor]
//        public FreeGiftSelectViewModel(
//            IMessageBoxService messageBoxService,
//            IUIVisualizerService uiVisualizerService)
//        {
//            #region Constructor.SetupServices
//            this.messageBoxService = messageBoxService;
//            this.uiVisualizerService = uiVisualizerService;
//            #endregion

//            #region Constructor.SetupCommands
//            #endregion

//            #region Constructor.SetupDataWrappers
//            #endregion

//            //cachedListOfDataWrappers =
//            //    DataWrapperHelper.GetWrapperProperties<LayananCabangViewModel>(this);

//            #region Constructor.SetupValidationRules
//            #endregion

//            #region Constructor.SetupCollections
//            FreeGiftFilter = new FreeGiftFilterViewModel(
//                messageBoxService,
//                uiVisualizerService);
//            FreeGiftFilter.FreeGiftSelectCommand = new SimpleCommand<Object, Object>(CanExecuteFreeGiftSelectCommand, ExecuteFreeGiftSelectCommand);
//            #endregion
//        }
//        #endregion

//        #region Public Properties

//        #region Public.Commands
//        #endregion

//        #region Public.ViewMode
//        #endregion

//        #region Public.Data
//        #endregion

//        #region Public.CachedCollection
//        #endregion

//        #region Public.DataVM
//        /// <summary>
//        /// </summary>
//        static PropertyChangedEventArgs selectedFreeGiftChangeArgs =
//            ObservableHelper.CreateArgs<FreeGiftSelectViewModel>(x => x.SelectedFreeGift);

//        public FreeGiftViewModel SelectedFreeGift
//        {
//            get { return selectedFreeGift; }
//            set
//            {
//                selectedFreeGift = value;
//                NotifyPropertyChanged(selectedFreeGiftChangeArgs);
//            }
//        }
//        /// <summary>
//        /// </summary>
//        static PropertyChangedEventArgs freeGiftFilterChangeArgs =
//            ObservableHelper.CreateArgs<FreeGiftSelectViewModel>(x => x.FreeGiftFilter);

//        public FreeGiftFilterViewModel FreeGiftFilter
//        {
//            get { return freeGiftFilter; }
//            set
//            {
//                freeGiftFilter = value;
//                NotifyPropertyChanged(freeGiftFilterChangeArgs);
//            }
//        }
//        #endregion

//        #endregion

//        #region Command Handlers
//        /// <summary>
//        /// </summary>
//        private bool CanExecuteFreeGiftSelectCommand(Object args)
//        {
//            return true;
//            //return FreeGiftFilter.KaryawansCV.CurrentPosition > -1;
//        }
//        /// <summary>
//        /// </summary>
//        private void ExecuteFreeGiftSelectCommand(Object args)
//        {
//            SelectedFreeGift = (FreeGiftViewModel) FreeGiftFilter.DataCV.CurrentItem;
//            if (SelectedFreeGift != null)
//            {
//                CloseActivePopUpCommand.Execute(true);
//            }
//        }
//        #endregion

//        #region IViewStatusAwareInjectionAware Members

//        //public void InitialiseViewAwareService(IViewAwareStatus viewAwareStatusService)
//        //{
//        //    this.ViewAwareStatusService = viewAwareStatusService;
//        //    //this.ViewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded;
//        //}
//        #endregion
        
//        #region Private Methods
//        //private void ViewAwareStatusService_ViewLoaded()
//        //{
//        //    LoadedKonsumenFilterViewModel = new KonsumenFilterViewModel(
//        //        uiVisualizerService,
//        //        ViewAwareStatusService);
//        //}

//        #endregion
//    }

//}
